package com.xiaok.smartclassroom.app.gateway.controller;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xiaok.smartclassroom.util.base.Result;
import com.xiaok.smartclassroom.util.enums.ResultEnum;
import org.apache.tomcat.jni.Error;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname HandlerController
 * @Description Web错误，全局处理。
 * @Date 2021/3/23 22:45
 * @Created by xiaok
 */
@Controller
public class HandlerErrorController implements ErrorController {

    private static Logger logger = LoggerFactory.getLogger(HandlerErrorController.class);

    private final String ERROR_PATH = "/error";
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    /**
     * Web页面错误处理
     */
    @RequestMapping(value = ERROR_PATH, produces = {"text/html"})
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        int code = response.getStatus();
        if (404 == code) {
            return new ModelAndView("error/404");
        } else if (403 == code) {
            return new ModelAndView("error/403");
        } else if (401 == code) {
            return new ModelAndView("login");
        } else {
            return new ModelAndView("error/500");
        }
    }

    /*
    * 请求处理
    * */
    @RequestMapping(value = ERROR_PATH)
    public Result<String> error(){

        RequestContext ctx = RequestContext.getCurrentContext();
        Throwable throwable = ctx.getThrowable();
        logger.error("系统异常",throwable);
        if( throwable !=null && throwable instanceof ZuulException){
            ZuulException e = (ZuulException)throwable;
            return  Result.error(e.nStatusCode, e.errorCause);
        }
        return Result.error(ResultEnum.ERROR);
    }




}
